package indi.kane.demandlist.configuration;

import com.alibaba.fastjson.JSON;
//import indi.kane.demandlist.service.impl.UserService;
import indi.kane.demandlist.service.impl.UserService;
import indi.kane.demandlist.vo.ResultVo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LoginInterceptor
 * @Author: kane
 * @Date: 2020-05-25 11:54 上午
 * @Description:
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        String res = "";
        Integer id = 0;
        Cookie[] cookies = request.getCookies();
        boolean result = false;
        if (cookies == null) {
            res = JSON.toJSONString(ResultVo.failed(ResultVo.NEEDLOGIN,"请先进行登录"));
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    id = cookie.getValue() == null
                            ? 0
                            : cookie.getValue() == "" ? 0 : Integer.valueOf(cookie.getValue());
                }
            }
            if (id.equals(0)) {
                res = JSON.toJSONString(ResultVo.failed(ResultVo.NEEDLOGIN,"请先进行登录"));
                result = false;
            } else {
                if (userService == null) {
                    BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
                    userService = (UserService) beanFactory.getBean("userService");
                }
                if (userService.selectByPrimaryKey(id) != null) {
                    result = true;
                } else {
                    res = JSON.toJSONString(ResultVo.failed(ResultVo.NEEDLOGIN,"请求篡改"));
                    result = false;
                }
            }
        }
        response.getOutputStream().write(res.getBytes());
        return result;
    }
}